﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abp.Domain.Repositories;
using Abp.Organizations;
using KelonProud.Administration.Domain.Authorization;
using KelonProud.Administration.Domain.Organizations;
using KelonProud.Linq;
using KelonProud.Mvc;

namespace KelonProud.Administration.Managers.Organizations
{
    public class KenlonOrganizationManager: KelonProudDomainService<KelonProudOrganizationUnit,long>
    {
        private readonly IRepository<KelonProudOrganizationUnit, long> _organizationUnitRepository;
        public KenlonOrganizationManager(IRepository<KelonProudOrganizationUnit, long> manageRepository) : base(manageRepository)
        {
            _organizationUnitRepository = manageRepository;
        }

        public long SaveNavigation(KelonProudOrganizationUnit organizationUnit)
        {
            CheckNavigationExits(organizationUnit);

            var result = ManagerRepository.InsertOrUpdateAndGetId(organizationUnit);
            UnitOfWorkManager.Current.SaveChanges();

            return result;
        }

        private void CheckNavigationExits(KelonProudOrganizationUnit organizationUnit)
        {
            if (List.Any(w => w.Id != organizationUnit.Id && w.ParentId == organizationUnit.ParentId && w.DisplayName == organizationUnit.DisplayName))
                throw new Exception("机构名称【{0}】在同父级机构下已存在".FormatWith(organizationUnit.DisplayName));

            if (List.Any(w => w.Id != organizationUnit.Id && w.ParentId == organizationUnit.ParentId && w.Code == organizationUnit.Code))
                throw new Exception("机构编码【{0}】在同父级机构下已存在".FormatWith(organizationUnit.Code));
        }

        /// <summary>
        /// 获取上级的区县。递归
        /// </summary>
        /// <param name="org"></param>
        /// <returns></returns>
        public KelonProudOrganizationUnit GetOrgLevel2(KelonProudOrganizationUnit org)
        {
            if (org.Level == 3||org.Level == 2 || org.Level == 1)
            {
                return org;
            }
            else
            {
                var pid = org.ParentId;
                KelonProudOrganizationUnit porg= _organizationUnitRepository.Get(pid.Value);
                return GetOrgLevel2(porg);
            }
        }

        public KelonProudOrganizationUnit GetFristUnitByLevel(int level)
        {
            return _organizationUnitRepository.FirstOrDefault(f => f.Level == 4);
        }

    }
}
